#include <iostream>
// OS
#include <pthread.h>
#include <unistd.h>

pthread_spinlock_t spin_lock;
int tickets = 10000; // 票

void *Route(void *args)
{
    int in = *(int *)args;

    while (true)
    {
        while (pthread_spin_lock(&spin_lock))
            ; // 得到锁，返回false；否则返回true反复申请，就是不阻塞
        if (tickets > 0)
        {
            std::cout << "I am thead-" << in << ", ticket is " << tickets-- << std::endl;
            pthread_spin_unlock(&spin_lock);
            //非临界区太短时，a刚释放锁，就能竞争锁（因为刚释放锁，离锁近(抽象理解)，争锁有优势），可能会出现反复是同一个线程打印
            usleep(100000);
        }
        else
        {
            pthread_spin_unlock(&spin_lock);
            break;
        }
    }

    delete (int *)args;
    return nullptr;
}
int main()
{
    pthread_spin_init(&spin_lock, PTHREAD_PROCESS_PRIVATE);
    int thread_num = 5;
    pthread_t tids[thread_num];
    // create thread
    for (size_t i = 0; i < thread_num; i++)
    {
        int *in = new int(i);
        pthread_create(tids + i, nullptr, Route, in);
    }
    // Join
    for (size_t i = 0; i < thread_num; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    pthread_spin_destroy(&spin_lock);

    return 0;
}